package conf

import (
	"os"
	"strings"
)

const DEFAULT_CRON_WAIT = 5000 // 默认退出等待时间
const DEFAULT_CONF_FILE = "/data/webroot/golang/crontab.conf"
const MIN_FIELDS_COUNT = 6

const (
	MinuteIndex = 0
	HourIndex   = 1
	DomIndex    = 2
	MonthIndex  = 3
	DowIndex    = 4
	NameIndex   = 5
	DescIndex   = 6
)

// Cron配置
type CronConfig struct {
	Domain        string `toml:"domain"` // 域名
	WaitGraceExit int    `toml:"waitGraceExit"`
	Content       string `toml:"content"`
	ConfFile      string `toml:"confFile"`
}

// 默认Cron配置
func DefaultCronConfig() (cronConfig *CronConfig) {
	cronConfig = &CronConfig{
		WaitGraceExit: DEFAULT_CRON_WAIT,
	}
	return
}

//加载cron执行计划配置
func loadCronContent() {
	confFile := DEFAULT_CONF_FILE
	if GEConf.CronConfig.ConfFile != "" {
		confFile = GEConf.CronConfig.ConfFile
	}

	cronContent, err := os.ReadFile(confFile)
	if err != nil && !os.IsNotExist(err){
		panic("读取cron配置文件失败，error:" + err.Error())
	}else if os.IsNotExist(err) {
		return
	}
	GEConf.CronConfig.Content = string(cronContent)
}

//将文本形式的cron格式化，去除无效的cron配置
func ParseCronContent() (cronList []string) {
	cronConfTemp := strings.Split(GEConf.CronConfig.Content, "\n")
	for _, cronText := range cronConfTemp {
		cronText = strings.TrimSpace(cronText)
		if len(cronText) > 0 && cronText[0] != '#' {
			cronList = append(cronList, cronText)
		}
	}
	return cronList
}
